package com.kede.app.service.impl;

import com.kede.app.converenum.FenxiaoStatusConverEnum;
import com.kede.app.converenum.GoodTypeConverEnum;
import com.kede.app.domain.LeescoreGoodTypeIds;
import com.kede.app.domain.LeescoreGoods;
import com.kede.app.ienum.TypeLevel;
import com.kede.app.po.GoodTypePo;
import com.kede.app.repository.LeescoreGoodTypeIdsRepository;
import com.kede.utils.ValidationUtil;
import com.kede.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.kede.app.repository.LeescoreGoodsRepository;
import com.kede.app.service.LeescoreGoodsService;
import com.kede.app.service.dto.LeescoreGoodsDto;
import com.kede.app.service.dto.LeescoreGoodsQueryCriteria;
import com.kede.app.service.mapstruct.LeescoreGoodsMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.kede.utils.PageUtil;
import com.kede.utils.QueryHelp;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @description 服务实现
* @author Pr.li
* @date 2023-05-23
**/
@Service
@RequiredArgsConstructor
public class LeescoreGoodsServiceImpl implements LeescoreGoodsService {

    private final LeescoreGoodsRepository leescoreGoodsRepository;
    private final LeescoreGoodsMapper leescoreGoodsMapper;

    private final LeescoreGoodTypeIdsRepository typeIdsRepository;

    @Value("${htmlImgSrc}")
    private String htmlImgSrc;


    private static String reg ="<[img|IMG].*?src=[\'|\"](.*?(?:[\\.jpg|\\.jpeg|\\.png|\\.gif|\\.bmp]))[\'|\"].*?[/]?>";

    private static Pattern imgsrcPattern = Pattern.compile(reg);

    //将图片的src添加上 http
    private String gethtml(String html){
        Matcher matcher = imgsrcPattern.matcher(html);
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            StringBuilder str = new StringBuilder();
            str.append("<img src=\"");
            boolean hasHttp = matcher.group(1).startsWith("http");
            if (hasHttp){
                str.append(matcher.group(1));
                str.append("\" style=\"max-width:100%;float:left;\">");
                matcher.appendReplacement(result, str.toString());
            }else{
                str.append(htmlImgSrc);
                str.append(matcher.group(1));
                str.append("\" style=\"max-width:100%;float:left;\">");
                matcher.appendReplacement(result, str.toString());
            }
        }
        System.out.println(result);
        return  result.toString();
    }

    @Override
    public Map<String,Object> queryAll(LeescoreGoodsQueryCriteria criteria, Pageable pageable){
        Page<LeescoreGoods> page = leescoreGoodsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        page.getContent().forEach(leescoreGoods -> {
            leescoreGoods.setBody(gethtml(leescoreGoods.getBody()));
            leescoreGoods.setRule(gethtml(leescoreGoods.getRule()));
        });
        return PageUtil.toPage(page.map(leescoreGoodsMapper::toDto));
    }

    @Override
    public List<LeescoreGoodsDto> queryAll(LeescoreGoodsQueryCriteria criteria){
        List<LeescoreGoods> all = leescoreGoodsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        all.forEach(leescoreGoods -> {
            leescoreGoods.setBody(gethtml(leescoreGoods.getBody()));
            leescoreGoods.setRule(gethtml(leescoreGoods.getRule()));
        });
        return leescoreGoodsMapper.toDto(all);
    }

    @Override
    @Transactional
    public LeescoreGoodsDto findById(Integer id) {
        LeescoreGoods leescoreGoods = leescoreGoodsRepository.findById(id).orElseGet(LeescoreGoods::new);
        ValidationUtil.isNull(leescoreGoods.getId(),"LeescoreGoods","id",id);
        return leescoreGoodsMapper.toDto(leescoreGoods);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LeescoreGoodsDto create(LeescoreGoods resources) {
        //新增初始化暂时用不倒的参数
        Long l = LocalDateTime.now().toEpochSecond(ZoneOffset.ofHours(8));
        resources.setCreatetime(l.intValue());
        resources.setUpdatetime(l.intValue());
        resources.setUsenum(0);
        resources.setFenxiaoStatus(FenxiaoStatusConverEnum.OFF);
        resources.setMaxBuyNumber(-1);
        resources.setType(GoodTypeConverEnum.DEBI);

        LeescoreGoods save = leescoreGoodsRepository.save(resources);
        GoodTypePo[] goodtypes = resources.getGoodtypes();
        List<LeescoreGoodTypeIds> saveall = new ArrayList<>();
        for (GoodTypePo goodtype : goodtypes) {
            LeescoreGoodTypeIds leescoreGoodTypeIds = new LeescoreGoodTypeIds();
            leescoreGoodTypeIds.setGoodId(save.getId());
            leescoreGoodTypeIds.setPid(0);
            leescoreGoodTypeIds.setGooTypeId(goodtype.getPid());
            LeescoreGoodTypeIds psave = typeIdsRepository.save(leescoreGoodTypeIds);
            for (Integer integer : goodtype.getChecked()) {
                LeescoreGoodTypeIds cGoodTypeIds = new LeescoreGoodTypeIds();
                cGoodTypeIds.setGoodId(save.getId());
                cGoodTypeIds.setPid(psave.getId());
                cGoodTypeIds.setGooTypeId(integer);
                saveall.add(cGoodTypeIds);
            }
        }
        typeIdsRepository.saveAllAndFlush(saveall);
        return leescoreGoodsMapper.toDto(save);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(LeescoreGoods resources) {
        LeescoreGoods leescoreGoods = leescoreGoodsRepository.findById(resources.getId()).orElseGet(LeescoreGoods::new);
        Long l = LocalDateTime.now().toEpochSecond(ZoneOffset.ofHours(8));
        leescoreGoods.setUpdatetime(l.intValue());
        ValidationUtil.isNull( leescoreGoods.getId(),"LeescoreGoods","id",resources.getId());
        leescoreGoods.copy(resources);
        //先删除之前的绑定关系
        typeIdsRepository.deleteAllByGoodId(resources.getId());
        GoodTypePo[] goodtypes = resources.getGoodtypes();
        List<LeescoreGoodTypeIds> saveall = new ArrayList<>();
        for (GoodTypePo goodtype : goodtypes) {
            LeescoreGoodTypeIds leescoreGoodTypeIds = new LeescoreGoodTypeIds();
            leescoreGoodTypeIds.setGoodId(leescoreGoods.getId());
            leescoreGoodTypeIds.setPid(0);
            leescoreGoodTypeIds.setGooTypeId(goodtype.getPid());
            LeescoreGoodTypeIds psave = typeIdsRepository.save(leescoreGoodTypeIds);
            for (Integer integer : goodtype.getChecked()) {
                LeescoreGoodTypeIds cGoodTypeIds = new LeescoreGoodTypeIds();
                cGoodTypeIds.setGoodId(leescoreGoods.getId());
                cGoodTypeIds.setPid(psave.getId());
                cGoodTypeIds.setGooTypeId(integer);
                saveall.add(cGoodTypeIds);
            }
        }
        typeIdsRepository.saveAllAndFlush(saveall);
        leescoreGoodsRepository.save(leescoreGoods);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            leescoreGoodsRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<LeescoreGoodsDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (LeescoreGoodsDto leescoreGoods : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("分类ID", leescoreGoods.getCategoryId());
            map.put("商品标题", leescoreGoods.getName());
//            map.put("出售模式:0=积分模式,1=货币模式,2=金钱+货币模式", leescoreGoods.getPaytype());
            map.put("商品类型: 0=实物商品,1=虚拟商品,2=积分", leescoreGoods.getType());
            map.put("商品状态:0=删除,1=仓库,2=上架", leescoreGoods.getStatus());
            map.put("商品发布时间", leescoreGoods.getCreatetime());
            map.put("商品详情", leescoreGoods.getBody());
            map.put("兑换规则", leescoreGoods.getRule());
            map.put("图片缩略图", leescoreGoods.getThumb());
            map.put("商品图集", leescoreGoods.getPics());
            map.put("权重排序", leescoreGoods.getWeigh());
            map.put("更新时间", leescoreGoods.getUpdatetime());
            map.put("商品库存", leescoreGoods.getStock());
            map.put("所需积分", leescoreGoods.getScoreprice());
            map.put("开放时间", leescoreGoods.getFirsttime());
            map.put("结束时间", leescoreGoods.getLasttime());
            map.put("价格", leescoreGoods.getMoney());
            map.put("已兑换", leescoreGoods.getUsenum());
            map.put("推荐:index=首页,hot=热门,recommend=推荐,new=最新", leescoreGoods.getFlag());
            map.put("限购数量", leescoreGoods.getMaxBuyNumber());
            map.put("商品分销: 0=不开启,1=开启", leescoreGoods.getFenxiaoStatus());
            map.put("运费", leescoreGoods.getExpressPrice());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }


}